<template>
  <view style="height: 100vh; background: #fff">
    <image class="bg" src="../../static/home/bg.png" mode="aspectFill" />
    <u-navbar title="" bgColor="rgba(0,0,0,0)" auto-back></u-navbar>
    <view class="con">
      <view class="title" v-if="type === '1'"> <text>图片</text>压缩 </view>
      <view class="title" v-if="type === '2'"> <text>视频</text>压缩 </view>
      <view class="title" v-if="type === '3'"> <text>文字</text>识别 </view>
      <view class="title" v-if="type === '4'"> <text>相片</text>模板 </view>
      <view class="title" v-if="type === '5'"> AI智能<text>抠图</text> </view>
      <view class="title" v-if="type === '6'"> AI<text>漫画风</text> </view>
      <view class="title" v-if="type === '7'"> 智能<text>卡通头像</text> </view>
      <view class="title" v-if="type === '8'"> AI一键<text>美化</text> </view>
      <view class="ctn" v-if="type === '1'">
        只需简单一点击，不仅能显著缩小图片大小，更能精确保证每一像素的高清晰度不受损，享受前所未有的便捷和效率。立即体验，一键压缩图片体积大小，并
        <text>保持图片清晰度</text>
      </view>
      <view class="ctn" v-if="type === '2'">
        一键压缩视频体积
        <view class="sub">支持上传视频类型：AVI、‌MKV、‌FLV、‌ WMV、‌MP4、‌MOV</view>
      </view>
      <view class="ctn" v-if="type === '3'">
        一键将图片文字转换成可编辑文本
        <view class="sub">支持上传图片类型：JPG,JPEG,PNG,BMP,GIF</view>
      </view>
      <view class="ctn" v-if="type === '4'"> 上传一张照片，一键生成打卡照片 </view>
      <view class="ctn" v-if="type === '5'"> 智能AI技术识别图片元素 </view>
      <view class="ctn" v-if="type === '6'"> 上传一张照片，一键生成二次元漫画 </view>
      <view class="ctn" v-if="type === '7'"> 上传一张照片，一键生成卡通头像 </view>
      <view class="ctn" v-if="type === '8'"> 上传一张照片，一键美化该照片 </view>
      <div v-if="type !== '4'">
        <view class="scBox" @click="scFn" v-if="!url">
          <div style="margin-bottom: 20rpx" v-if="type !== '2'">
            <u-icon name="photo-fill" size="40"></u-icon>
          </div>
          <div style="margin-bottom: 20rpx" v-if="type === '2'">
            <image class="sp" src="../../static/home/sp.png" mode="aspectFill" />
          </div>
          <view class="btn">
            <u-button type="primary" shape="circle"><image class="icon" src="../../static/home/scb.png" mode="aspectFill" /> 上传{{ type === "2" ? "视频" : "图片" }} </u-button>
          </view>
        </view>
        <image :src="url" v-else style="width: 396px; height: 223px; margin: 30rpx 0" mode="aspectFill" />
      </div>
      <div v-else style="text-align: center; margin-top: 20rpx">
        <image :src="currentTem?.preview" style="width: 534rpx; height: 692rpx" alt="" mode="aspectFill" />
        <view style="margin: 30rpx 0" @click="goPage('/pages/home/templateList')">更多模板</view>
        <view class="btn">
          <u-button type="primary" shape="circle" @click="scFn">立即制作 </u-button>
        </view>
      </div>
      <view class="freeText" v-if="level === '0'">免费次数剩余:{{ freeCount }}</view>
      <view class="vipBox" v-if="level === '0' && platShow">
        <view class="l">开通会员享无限次数</view>
        <view style="width: 220rpx">
          <u-button type="primary" @click="goPage('/pages/myPage/openMembership')" color="#5f5a50" shape="circle">开通会员</u-button>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { addUseRecord, cartoonAvatar, cartoonPhoto, compressPhoto, cutoutPhoto, getFreeCount, ocrPhoto } from "@/api/home";
import { cartoonResult, configKey, getTemplateList, getUserInfo } from "@/api/my";
import { useFilesStore } from "@/stores/files";
import { goPage } from "@/utils/commonFn";
import { BASE_UPLOADURL, BASE_URL } from "@/utils/request";
//@ts-ignore
import { onShow } from "@dcloudio/uni-app";
import { onMounted, ref } from "vue";
const { type } = defineProps<{
  type: "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8";
}>();
const url = ref("");
const freeCount = ref(0);
const apiTypeInfo: any = {
  "1": "image_compress",
  "2": "video_compress",
  "3": "ocr",
  "4": "photo_template",
  "5": "cutout",
  "6": "cartoon",
  "7": "cartoon_avatar",
  "8": "beautify",
};
const level = ref("");
const currentTem = ref();
const platShow = ref(true);
onMounted(async () => {
  const res: any = await getTemplateList({
    pageNum: 1,
  });
  currentTem.value = res.rows[0];
  const res1 = await configKey("ios_pay_switch");
  uni.getSystemInfoAsync({
    success: (res) => {
      console.log(res.platform);
      if (res.platform === "ios" && res1.data === "false") {
        platShow.value = false;
      } else {
        platShow.value = true;
      }
    },
  });
});
onShow(async () => {
  url.value = "";
  const res = await getUserInfo();
  level.value = res.data.level;
  if (apiTypeInfo[type]) {
    const res = await getFreeCount({
      apiType: apiTypeInfo[type],
    });
    freeCount.value = res.data;
  }
  if (useFilesStore().useTemplate) {
    currentTem.value = useFilesStore().useTemplate;
  }
});
const scFn = () => {
  if (type === "1") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "压缩中",
          });
          uni.uploadFile({
            url: BASE_UPLOADURL,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              uni.showLoading({
                title: "压缩中",
              });
              url.value = JSON.parse(uploadFileRes.data).data.url;
              const res1 = await compressPhoto({ url: url.value });
              console.log(res1);
              useFilesStore().setVideoInfo({ url: res1.data.url, originSize: res1.data.sourceSize, targetSize: res1.data.targetSize });

              goPage(`/pages/home/compressDetails?type=${type}`);
              uni.hideLoading();
            },
          });
        }
      },
    });
  } else if (type === "2") {
    let obj = {
      originSize: 0,
      targetSize: 0,
      width: 0,
      height: 0,
      url: "",
    };
    uni.chooseVideo({
      sourceType: ["camera", "album"],
      success: async function (res) {
        uni.showLoading({
          title: "压缩中",
        });
        uni.getVideoInfo({
          src: res.tempFilePath,
          success: (res) => {
            console.log(res, "原视频");
            obj.originSize = res.size;
          },
          fail: (err) => {
            console.log(err);
          },
        });
        await addUseRecord({ apiType: "video_compress" });
        uni.compressVideo({
          src: res.tempFilePath,
          quality: "high",
          success: (res) => {
            console.log(res, "压缩后");

            uni.uploadFile({
              url: BASE_UPLOADURL,
              filePath: res.tempFilePath,
              name: "file",
              header: {
                Authorization: uni.getStorageSync("token"),
              },
              success: async (uploadFileRes) => {
                obj.url = JSON.parse(uploadFileRes.data).data.url;

                uni.getVideoInfo({
                  src: res.tempFilePath,
                  success: (res1) => {
                    obj.targetSize = res1.size;
                    useFilesStore().setVideoInfo(obj);
                    goPage(`/pages/home/compressDetails?type=${type}`);
                  },
                  fail: (err) => {
                    console.log(err);
                  },
                });
              },
            });
          },
          fail: (err) => {
            console.log(err);
          },
        });
        uni.hideLoading();
      },
    });
  } else if (type == "3") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "识别中",
          });
          uni.uploadFile({
            url: BASE_UPLOADURL,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              url.value = JSON.parse(uploadFileRes.data).data.url;
              const res1 = await ocrPhoto({ url: url.value });
              console.log(res1);
              useFilesStore().setVideoInfo({ url: url.value, text: res1.data });

              goPage(`/pages/home/compressDetails?type=${type}`);
              uni.hideLoading();
            },
          });
        }
      },
    });
  } else if (type == "4") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "识别中",
          });
          uni.uploadFile({
            url: BASE_UPLOADURL,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              await addUseRecord({ apiType: "photo_template" });

              url.value = JSON.parse(uploadFileRes.data).data.url;
              useFilesStore().setVideoInfo({ url: url.value, ...currentTem.value });

              goPage(`/pages/home/photoBox`);
              uni.hideLoading();
            },
          });
        }
      },
    });
  } else if (type == "5") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "识别中",
          });
          uni.uploadFile({
            url: BASE_UPLOADURL,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              uni.showLoading({
                title: "识别中",
              });
              url.value = JSON.parse(uploadFileRes.data).data.url;
              const res1 = await cutoutPhoto({ url: url.value });
              console.log(res1);
              useFilesStore().setVideoInfo({ url: url.value, resUrl: res1.data });
              goPage(`/pages/home/cutoutPage`);

              uni.hideLoading();
            },
          });
        }
      },
    });
  } else if (type == "6") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "识别中",
          });
          uni.uploadFile({
            url: BASE_UPLOADURL,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              uni.showLoading({
                title: "识别中",
              });
              url.value = JSON.parse(uploadFileRes.data).data.url;
              const res1 = await cartoonPhoto({ url: url.value });
              const res3 = await cartoonResult({ requestId: res1.data });
              let timer: any;
              if (!res3.data) {
                timer = setInterval(async () => {
                  const res3 = await cartoonResult({ requestId: res1.data });
                  if (res3.data) {
                    useFilesStore().setVideoInfo({ url: url.value, resUrl: res3.data });
                    goPage(`/pages/home/cartoonPage`);
                    clearInterval(timer);
                    uni.hideLoading();
                  }
                }, 3000);
              } else {
                useFilesStore().setVideoInfo({ url: url.value, resUrl: res3.data });
                goPage(`/pages/home/cartoonPage`);
                clearInterval(timer);
                uni.hideLoading();
              }
            },
          });
        }
      },
    });
  } else if (type == "7") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "识别中",
          });
          uni.uploadFile({
            url: BASE_UPLOADURL,
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              uni.showLoading({
                title: "识别中",
              });
              url.value = JSON.parse(uploadFileRes.data).data.url;
              const res1 = await cartoonAvatar({ url: url.value });
              console.log(res1);
              useFilesStore().setVideoInfo({ url: url.value, resUrl: res1.data });
              goPage(`/pages/home/cartoonPage`);

              uni.hideLoading();
            },
          });
        }
      },
    });
  } else if (type == "8") {
    uni.chooseImage({
      count: 1, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], //从相册选择或者打开相机
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0, len = tempFilePaths.length; i < len; i++) {
          uni.showLoading({
            title: "美化中",
          });
          uni.uploadFile({
            url: BASE_URL + "/external/photo/beautify",
            filePath: tempFilePaths[i],
            name: "file",
            header: {
              Authorization: uni.getStorageSync("token"),
            },
            success: async (uploadFileRes) => {
              url.value = JSON.parse(uploadFileRes.data).data;
              if (JSON.parse(uploadFileRes.data).code === 200) {
                console.log(url.value);

                useFilesStore().setVideoInfo({ url: tempFilePaths[i], resUrl: url.value });
                goPage(`/pages/home/beautifyPage`);

                uni.hideLoading();
              } else {
                uni.showToast({
                  title: JSON.parse(uploadFileRes.data).msg,
                  icon: "none",
                });
              }
            },
          });
        }
      },
    });
  }
};
</script>
<style lang="less" scoped>
.bg {
  width: 100%;
  height: 1362rpx;
  position: absolute;
  left: 0;
  z-index: 1;
}
.con {
  position: relative;
  padding: 0 30rpx;
  z-index: 2;
  padding-top: 110rpx;
  .title {
    text-align: center;
    margin-top: 70rpx;
    font-size: 52rpx;
    text {
      color: #3b70fd;
    }
  }
  .ctn {
    font-size: 28rpx;
    color: #767676;
    margin-top: 58rpx;
    line-height: 46rpx;
    text-align: center;
    padding: 0 20rpx;
    text {
      color: #333333;
      border-bottom: 1rpx solid #c3bef3;
    }
    .sub {
      color: #333333;
    }
  }

  .scBox {
    display: flex;
    flex-wrap: wrap;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 32rpx 32rpx 32rpx 32rpx;
    border: 2rpx dashed #767676;
    padding: 75rpx 154rpx;
    justify-content: center;
    margin-top: 80rpx;
    margin-bottom: 56rpx;
    .icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 12rpx;
    }
    .sp {
      width: 48rpx;
      height: 48rpx;
    }
  }
  .freeText {
    font-size: 30rpx;
    color: #767676;
    text-align: center;
  }
  .vipBox {
    display: flex;
    justify-content: space-between;
    margin-top: 56rpx;
    background: linear-gradient(-270deg, #f5e2c9 0%, #f2cc90 100%);
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    padding: 22rpx 34rpx;
    align-items: center;
    .l {
      width: 70%;
      font-size: 28rpx;
      color: #3d3d3d;
    }
  }
}
.btn {
  box-shadow: 0rpx 20rpx 30rpx 0rpx rgba(100, 73, 218, 0.3);
  width: 400rpx;
  margin: 40rpx auto;
  border-radius: 60rpx 60rpx 60rpx 60rpx;
}
</style>
